<template>
  <div id="aCoursesList" class="bg-fa of">
    <section class="container" style="margin-bottom: 1px">
      <el-row class="tac" :gutter="28" style="height: 478px">
        <el-col :span="1" style="margin-top: 10px">
          <el-badge :value="tips" class="item">
          <el-button icon="el-icon-plus" circle @click="openAdd()"></el-button>
          </el-badge>
        </el-col>
        <el-drawer
          title="我是标题"
          :visible.sync="drawer"
          :with-header="false"
        >
          <el-tag type="danger">搜索好友</el-tag>
          <el-dropdown>
            <el-input
              placeholder="请输入内容"
              v-model="input"
              clearable
              class="el-dropdown-link"
            >
            </el-input>
            <el-dropdown-menu slot="dropdown" v-if="showmenber">
              <el-dropdown-item v-for="item in menber" :key="item.id" style="width: auto">
                <img
                  :src="item.avatar"
                  width="30"
                  height="30"
                  class="vam picImg"
                  alt
                >
                <span style="width: 130px">{{item.nickname}}</span>
                <el-button size="mini" round style="float: right" @click="sendAdd(item.id)">添加</el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-divider></el-divider>
          <el-tag type="danger">申请好友列表</el-tag>
          <el-table
            :data="AddMeList"
            stripe
            style="width: 100%">
            <el-table-column
              label="头像"
              width="180">
              <template slot-scope="scope">
                <img
                  :src="scope.row.avatar"
                  width="50"
                  height="50"
                  class="vam picImg"
                  alt
                >
              </template>
            </el-table-column>
            <el-table-column
              label="用户名"
              width="180">
              <template slot-scope="scope">
                <div slot="reference" class="name-wrapper">
                  <el-tag size="medium">{{ scope.row.nickname }}</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="handleAccept(scope.row.her_id)">接受</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-divider></el-divider>
        </el-drawer>
        <section class="no-data-wrap" v-if="tips1">
          <em class="icon30 no-data-ico">&nbsp;</em>
          <span class="c-666 fsize14 ml10 vam">还没有好友噢...</span>
        </section>
        <section class="no-data-wrap" v-if="tips2">
          <em class="icon30 no-data-ico">&nbsp;</em>
          <span class="c-666 fsize14 ml10 vam">请先登陆...</span>
        </section>
        <el-col :span="2">
          <el-menu
            default-active="2"
            class="el-menu-vertical-demo"
          v-for="item in this.friends"
            :key="item.id"
            style="width: 150px;margin-top: 10px"
          >
            <el-badge value="" class="item" :ref="item.id">
            <el-menu-item :index="item.id" @click="changeChat(item.id)">
              <el-avatar :src="item.avatar" style="margin-right: 10px"></el-avatar>
              <span class="title">{{ item.nickname }}</span>
            </el-menu-item>
            </el-badge>
          </el-menu>
        </el-col>
        <el-col :span="20">
            <JwChat-index :config="config" :taleList="taleList" @enter="bindEnter" v-model="inputMsg" :toolConfig="tool"  v-if="isshow" scrollType="scroll"/>
        </el-col>
      </el-row>
    </section>
  </div>
</template>

<script>
  import friend from "@/api/friend"
  import cookie from 'js-cookie'
  import userApi from '@/api/login'
  export default {
    data () {
      return {
        tips1:false,
        tips2:false,
        incahtId: '',
        tips: null,
        showmenber: false,
        input: '',
        drawer: false,
        menber: {
          avatar: '',
          nickname: '',
        },
        addFriend:{
          add: '+',
          own_id: '',
          her_id: '',
        },
        AddMeList:{},
        isshow:false,
        friends:{},
        inputMsg: '',
        taleList: [
        ],
        tool: {
          show: ['history'],
          callback: this.toolEvent
        },
        config: {
          img: '../image/cover.png',
          name: 'JwChat',
          callback: this.headerEvent,
          her_id: '',
        },
        loginInfo: {
          id: '',
          age: '',
          avatar: '',
          mobile: '',
          nickname: '',
          sex: ''
        },
      }

    },
    watch:{
      input :'getMenber'

    },
    //初始化第一个聊天对象
    created() {
      friend.getFreind().then(response => {
        this.friends=response.data.data.friends
        var menber=cookie.get('ljh_ucenter', {domain: 'linjiahao.xyz'})
        if(menber==""){
          this.tips2=true
        }else {
          this.loginInfo=JSON.parse(cookie.get('ljh_ucenter', {domain: 'linjiahao.xyz'}))
          if(this.friends==""){
            this.tips1=true
          }
          this.initWebSocket()
        }

      })
    },
    destroyed() {
      this.websock.close()
    },
    methods: {
      openAdd(){
        if(this.loginInfo.id==""){
          this.$message({
            type:"error",
            message:"请先登陆"
          })
        }else {
          this.drawer=true
        }
      },
      handleAccept(id){
        userApi.AddMeList(id).then(response =>{
          console.log(this.AddMeList)
          this.AddMeList.forEach((value,index,array)=>{
            if(value.her_id==id){
              this.AddMeList.splice(value,1)
            }
          })
          this.$message({
            type:"success",
            message:"好友+1"
          })
          friend.getFreind().then(response => {
            this.friends=response.data.data.friends
            if(this.tips!=1){
              this.tips=this.tips-1
            }else {
              this.tips=null
            }
          })
        })
      },
      getMenber(){
        userApi.getMenber(this.input).then(response => {
          this.showmenber=true
          this.menber=response.data.data.menber
        })

      },
      //发送添加好友信息
      sendAdd(uid){
        this.addFriend.own_id=this.loginInfo.id
        this.addFriend.her_id=uid
        console.log(this.addFriend)
        this.websocketsend(JSON.stringify(this.addFriend));
        this.$message({
          type:"success",
          message:"发送成功"
        })
      },
      getNowFormatDate() {
        var date = new Date();
        var seperator1 = "/";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
          month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
          strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
          + " " + date.getHours() + seperator2 + date.getMinutes()
          + seperator2 + date.getSeconds();
        return currentdate;
      },
      //发送信息
      bindEnter () {
        const msg = this.inputMsg
        if (!msg) return;
        var myDate = this.getNowFormatDate();
        var a=JSON.parse(cookie.get('ljh_ucenter', {domain: 'linjiahao.xyz'}))
        console.log(this.config.her_id)
        const msgObj = {
          "date": myDate,
          "text": { "text": msg },
          "mine": true,
          "name": a.nickname,
          "img": a.avatar,
          "her_id": this.config.her_id,
          "myid": a.id,
        }
        this.taleList.push(msgObj)
        this.websocketsend(JSON.stringify(msgObj));
      },
      toolEvent (type) {
        console.log('tools', type)
      },
      headerEvent (type) {
        console.log('header', type)
      },
      changeChat(id){
        this.incahtId=id
        for(var i in this.friends){
          if(this.friends[i].id==id){
            this.isshow=true
            this.config.img=this.friends[i].avatar
            this.config.name=this.friends[i].nickname
            this.config.her_id=this.friends[i].id
            this.getFriendMessage(id)
          }
        }
      },
      getFriendMessage(id){
        this.taleList=[]
        friend.getMessage(id).then(response =>{
          for(var i in response.data.data.chatmessage){
            var mine=true
            if(response.data.data.chatmessage[i].mine==0){
              mine=false
            }
            const msgObj = {
              "date": response.data.data.chatmessage[i].data ,
              "text": { "text": JSON.parse(response.data.data.chatmessage[i].text).text },
              "mine": mine,
              "name": response.data.data.chatmessage[i].nickname,
              "img": response.data.data.chatmessage[i].img,
            }
            this.taleList.push(msgObj)
          }
        })
      },
      //websocket
      initWebSocket(){ //初始化weosocket
        const wsuri = "ws://58.87.127.144:8021/ws";
        this.websock = new WebSocket(wsuri);
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onopen = this.websocketonopen;
        this.websock.onerror = this.websocketonerror;
        this.websock.onclose = this.websocketclose;
      },
      websocketonopen(){ //连接建立之后执行send方法发送数据
        this.websocketsend(JSON.stringify(this.loginInfo));
      },
      websocketonerror(){//连接建立失败重连
        this.initWebSocket();
      },
      websocketonmessage(e){ //数据接收
        const redata = JSON.parse(e.data);
        if(redata.mine!=null){
          var myid=redata.myid
          console.log(myid)
          var num=1+Number(this.$refs[myid][0].value)
          this.$refs[myid][0].value=num.toString()
          if(this.isshow && myid==this.incahtId){
            const msgObj = {
              "date": redata.data,
              "text": { "text": JSON.parse(redata.text).text },
              "mine": false,
              "name": redata.nickname,
              "img": redata.img,
            }
            this.taleList.push(msgObj)
          }
          return;
        }
        if(redata.do_number==1){
          this.tips+=1;
          return
        }
        if(redata[0][0].do_number==2){
          this.AddMeList=redata[0]
          return;
        }
      },
      websocketsend(Data){//数据发送
        this.websock.send(Data);
      },
      websocketclose(e){  //关闭
        console.log('断开连接',e);
      },
    }

  }
</script>

<style>

</style>
